package com.example.sandbox.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class UrlInterceptor implements HandlerInterceptor{

    @Value("${platform.name}")
    private String platformName;

    private static final List<String> pay58Urls = new ArrayList<>();
    static {
        // 初始化列表，添加有效的 URL
        pay58Urls.addAll(Arrays.asList(
                "/gateway/v1/pay/brazil/charge",
                "/gateway/v1/pay/brazil/cashOut/submit",
                "/gateway/v1/sandbox/charge/simulatePaymentS/{tradeNo}",
                "/gateway/v1/sandbox/charge/simulatePaymentF/{tradeNo}",
                "/gateway/v1/pay/brazil/queryCharge",
                "/gateway/v1/sandbox/transfer/simulatePaymentS/{tradeNo}",
                "/gateway/v1/sandbox/transfer/simulatePaymentF/{tradeNo}",
                "/gateway/v1/pay/brazil/cashOut/query"
        ));
    }
    private static final List<String> uuPayUrls = new ArrayList<>();
    static {
        // 初始化列表，添加有效的 URL
        uuPayUrls.addAll(Arrays.asList(
                "/api/v1/pay/brazil/order",
                "/api/v1/pay/brazil/transferOrder",
                "/api/v1/sandbox/order/simulatePaymentS/{payOrderId}",
                "/api/v1/sandbox/order/simulatePaymentF/{payOrderId}",
                "/api/v1/pay/brazil/queryOrder",
                "/api/v1/sandbox/transfer/simulatePaymentS/{transferId}",
                "/api/v1/sandbox/transfer/simulatePaymentF/{transferId}",
                "/api/v1/pay/brazil/transfer/query"
        ));
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        List<String> allowedUrls;

        // 排除 /error 路径
        if ("/error".equals(requestUri)) {
            return true;
        }

        // 根据 platformName 选择允许的 URL 列表
        if ("58".equals(platformName)) {
            allowedUrls = pay58Urls;
        } else if ("uu".equals(platformName)) {
            allowedUrls = uuPayUrls;
        } else if ("all".equals(platformName)) {
            allowedUrls = new ArrayList<>(uuPayUrls);
            allowedUrls.addAll(pay58Urls);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }

        // 检查请求的 URI 是否与允许的 URL 匹配
        boolean isAllowed = allowedUrls.stream()
                .anyMatch(pattern -> Pattern.matches(convertToRegex(pattern), requestUri));

        if (!isAllowed) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 返回 404
            return false; // 终止请求
        }
        return true; // 继续处理请求
    }

    // 将 URL 模式转换为正则表达式
    private String convertToRegex(String pattern) {
        return pattern
                .replace("{tradeNo}", "\\w+")   // 匹配字母数字字符
                .replace("{payOrderId}", "\\w+") // 匹配字母数字字符
                .replace("{transferId}", "\\w+"); // 匹配字母数字字符
    }
}